package huixue.cn.com.rxapp.helper;

import java.lang.reflect.Field;

import huixue.cn.com.rxapp.base.IBaseUI;
import huixue.cn.com.rxapp.util.LogUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by gongdongyang 2019/7/23
 * Describe:
 */
public class RxSchedulersHelper {

    private static final String TAG = "RxSchedulersHelper";

    public static <T> ObservableTransformer<T, T> io_main() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(Schedulers.computation())
                        //.doOnNext(sTokenChecker)
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


    public static <T> ObservableTransformer<T, T> io_main(IBaseUI ui) {
        if (ui == null) {
            return observable -> observable.subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.computation())
                    //.doOnNext(sTokenChecker)
                    .observeOn(AndroidSchedulers.mainThread());
        } else {
            return observable -> observable.subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.computation())
                    //.doOnNext(sTokenChecker)
                    .observeOn(AndroidSchedulers.mainThread())
                    .filter(data -> ui.isAlive());
        }
    }


    private static Consumer sTokenChecker = new Consumer() {

        final String STATUE_TOKEN_ERROR = String.valueOf(2014);

        @Override
        public void accept(Object o) throws Exception {
            if (o == null) {
                return;
            }
            try {
                Class c = o.getClass();
                Field codeField = c.getDeclaredField("code");
                codeField.setAccessible(true);
                Object statusObj = codeField.get(o);
                LogUtils.d(TAG,"c=="+c.getName());
                //

            } catch (Exception ignored) {
            }
        }
    };

}
